//
//  THJSearchVC.m
//  THJXHW
//
//  Created by 河南德艺 on 17/3/8.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJSearchVC.h"
#import "MJRefresh.h"
#import "THJDBManger.h"
#import "ZBNetworking.h"
#import "THJDataProduceCell.h"
#import "THJProductDetailVC.h"
@interface THJSearchVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSInteger page;
    NSString * _keyword;
    UITableView * _tableview;
}
@property (weak, nonatomic) IBOutlet UITextField *searchTF;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@property (strong, nonatomic)  UIView *hotSearchView;
@property (strong, nonatomic)  NSMutableArray *listArr;
@end

@implementation THJSearchVC
-(NSMutableArray*)listArr{
    if(!_listArr){
        _listArr = [[NSMutableArray alloc] init];
    }
    return _listArr;
}
-(UIView*)hotSearchView{
    if(!_hotSearchView){
        _hotSearchView = [[UIView alloc] init];
        CGFloat space;
        if(KIsiPhoneX){
            space = 44+44+20+20;
        }else{
            space = 20+44+20+20;
        }
        _hotSearchView.frame = CGRectMake(0, space, ScreenWidth, ScreenHeight);
        [self.view addSubview:_hotSearchView];
    }
    return _hotSearchView;
}
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setHidden:YES];
    [self setStateBarColor:MainColor];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    
    if (KIsiPhoneX) {
        self.topSpace.constant = 44;
    }
    page = 1;
    [super viewDidLoad];
    [self setStateBarColor:COLOR(83, 84, 85, 1)];
    self.searchTF.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    self.searchTF.delegate = self;//设置代理
    [self setTextFieldLeftImageView:self.searchTF leftImageName:@"搜索"];
    if([self.formType isEqual:@"全部分类"]){
        _keyword = self.keyword;
        self.textFiled.text = self.keyword;
        [self searchDataWithKeyword:self.keyword PageNo:1];
    }else{
        [self setHotSearchBtns];
    }
}
-(void)searchDataWithKeyword:(NSString*)keyword PageNo:(NSInteger)page{
    [MBProgressHUD showMessage:@"" toView:self.view];
    __weak typeof(self) weakself = self;
    NSString * url = [NSString stringWithFormat:@"%@index.php?f=sell_5&r=sell_5&keyword=%@&pape=%ld",THJUrlDomain,keyword,page];
    url =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"搜索列表-%@",url);
    [THJNetWork getNetDataFromUrl:url callback:^(NSDictionary * responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if([responseObject[@"status"] isEqual:@"200"]){
            if([responseObject[@"nexpage"] isEqual:@"end"]){
                [_tableview.mj_footer endRefreshingWithNoMoreData];
            }
            [weakself.hotSearchView removeFromSuperview];
            NSLog(@"搜索词-%@-%@",keyword,_keyword);
            if(![keyword isEqual:_keyword]){
                NSLog(@"YY");
                [weakself.listArr removeAllObjects];
            }
            NSLog(@"NN");
            for (NSDictionary * dic  in responseObject[@"data"]){
                [weakself.listArr addObject:dic];
            }
             _keyword = keyword;
            CGFloat constant;
            if(KIsiPhoneX){
                constant = 99;
            }else{
                constant = 64;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
             _tableview =  [weakself setTableviewWithFrame:CGRectMake(0, constant, ScreenWidth, ScreenHeight - constant) RegisterNibNameArr:@[@"THJDataProduceCell"] ReuseIdentifierArr:@[@"list"] RowHeight:110 BgColor:SingleColor(whiteColor) IsLoadMore:YES];
            });
        }else{
            [self HUDShowMsg:@"没有相关信息" AfterDelayDimiss:1];
        }
    }];
}
-(void)loadMore{
    page++;
    [self searchDataWithKeyword:self.textFiled.text PageNo:page];
    NSLog(@"下拉加载");
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.listArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = self.listArr[indexPath.row];
    THJDataProduceCell * cell = [tableView dequeueReusableCellWithIdentifier:@"list" forIndexPath:indexPath];
    [cell setCellContentWithDic:dic];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic  = self.listArr[indexPath.row];
    THJProductDetailVC * vc  = [[THJProductDetailVC alloc] init];
    vc.itemid = dic[@"itemid"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)setHotSearchBtns{
    NSMutableArray *testArray = [NSMutableArray array];
    [testArray addObject:@"硅锰6517"];
    [testArray addObject:@"高碳铬铁"];
    [testArray addObject:@"硅铁"];
    [testArray addObject:@"硅铁72"];
    [testArray addObject:@"低碳铬铁"];
    [testArray addObject:@"钒铁"];
    [testArray addObject:@"增碳剂"];
    [testArray addObject:@"锰铁"];
    [testArray addObject:@"铝铁"];
    [testArray addObject:@"硅铝铁"];
    
    CGFloat startX = 10;
    CGFloat startY = 15;
    CGFloat buttonHeight = 30;
    
    for(int i = 0; i < 10; i++)
    {
        UIButton *btn = [[UIButton alloc]init];
        btn.backgroundColor = COLOR(237, 237, 237, 1);
        btn.layer.cornerRadius = 5;
        [btn setTitle:testArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:COLOR(26, 26, 26, 1) forState:UIControlStateNormal];
        [btn setFont:[UIFont systemFontOfSize:13]];
        [btn addTarget:self action:@selector(hotSearchAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.hotSearchView addSubview:btn];
        
        CGSize titleSize = [testArray[i] sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:btn.titleLabel.font.fontName size:btn.titleLabel.font.pointSize]}];
        
        titleSize.height = 20;
        titleSize.width += 20;
        
        if(startX + titleSize.width > [UIScreen mainScreen].bounds.size.width){
            startX = 10;
            startY = startY + buttonHeight + 10;
        }
        btn.frame = CGRectMake(startX, startY, titleSize.width, buttonHeight);
        startX = CGRectGetMaxX(btn.frame) + 10;
    }
}
-(void)hotSearchAction:(UIButton*)btn{
    if([_keyword isEqual:btn.titleLabel.text]){
        return;
    }else{
        self.searchTF.text = btn.titleLabel.text;
        [self searchDataWithKeyword:btn.titleLabel.text PageNo:page];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([_keyword isEqual:self.textFiled.text]){
        return NO;
    }else{
        [self.view endEditing:YES];
        [self searchDataWithKeyword:self.textFiled.text PageNo:page];
    }
    return YES;

}
- (IBAction)didSearchBtnSction:(id)sender {
    if(self.textFiled.text.length){
        if([_keyword isEqual:self.textFiled.text]){
            return;
        }else{
            [self searchDataWithKeyword:self.textFiled.text PageNo:page];
        }
    }
}
- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
